<template>
  <el-dialog v-model=parentDialogFormVisible :title="labelPosition" @close="closeDialog" width="30%">
    <el-radio-group style="margin-bottom: 10px" v-model="labelPosition">
      <el-radio-button label="登录" @click="resetForm">登录</el-radio-button>
      <el-radio-button label="注册" @click="resetForm">注册</el-radio-button>
    </el-radio-group>
    <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        label-width="70px"
        class="demo-ruleForm"
    >
      <el-form-item label="登录身份" porop="identityCode" v-if="labelPosition === '注册'">
        <el-radio-group v-model="loginForm.identityCode">
          <el-radio :label="1">普通用户</el-radio>
          <el-radio :label="2">商家</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="农场名" prop="nickname" v-if="labelPosition === '注册' && loginForm.identityCode === 2">
        <el-input
            v-model.trim="loginForm.nickname"
            placeholder="为您的农场起一个引人注目的名字吧"
            clearable
            maxlength="16"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname" v-if="labelPosition === '注册' && loginForm.identityCode === 1">
        <el-input
            v-model.trim="loginForm.nickname"
            placeholder="为您的账号起一个不错的昵称吧"
            clearable
            maxlength="16"
        />
      </el-form-item>
      <el-form-item label="账号" prop="account" >
        <el-input
            v-model.trim="loginForm.account"
            placeholder="请输入您的账号"
            clearable
            maxlength="32"
        />
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input
            v-model="loginForm.pass"
            placeholder="请输入您的密码"
            type="password"
            autocomplete="off"
            show-password
            clearable
            maxlength="32"
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input
            v-model="loginForm.checkPass"
            placeholder="请再次输入您的密码"
            type="password"
            autocomplete="off"
            show-password
            clearable
            maxlength="32"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNum" v-if="labelPosition === '注册'">
        <el-input
            v-model.number="loginForm.phoneNum"
            placeholder="请输入您的手机号码"
            clearable
            maxlength="11"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="danger" @click="resetForm">重置</el-button>
      <el-button type="success" @click="commit">{{ labelPosition }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {reactive, ref} from "vue";
import request from "@/http/request";

export default {
  name: "Login&SignUp",
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false
    }
  },
  emits: {
    closeDialog: {
    },
  },
  data() {
    return {
      parentDialogFormVisible: this.dialogFormVisible,
      labelPosition: "登录",
      loginFormRef: ref(null),
      loginForm: reactive({
        identityCode: 1,
        nickname: '',
        account: '',
        pass: '',
        checkPass: '',
        phoneNum: '',
      }),
      rules: reactive({
        nickname: [{ validator: this.validateNickname, trigger: 'blur' }],
        account: [{ validator: this.validateAccount, trigger: 'blur' }],
        pass: [{ validator: this.validatePass, trigger: 'blur' }],
        checkPass: [{ validator: this.validatePass2, trigger: 'blur' }],
        phoneNum: [{ validator: this.validatePhoneNum, trigger: 'blur' }],
      }),
    }
  },
  watch: {
    dialogFormVisible: function(newVal){
      this.parentDialogFormVisible = newVal;
    }
  },
  methods: {
    validateNickname: function(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入您的昵称！'))
      } else {
        callback()
      }
    },
    validateAccount: function(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入您的账号！'))
      } else {
        callback()
      }
    },
    validatePass: function(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入密码！'))
      } else if (value.length < 6) {
        callback(new Error('密码长度不足六位！'))
      } else {
        callback()
      }
    },
    validatePass2: function (rule, value, callback) {
      if (value === '') {
        callback(new Error('请再次输入密码！'))
      } else if (value.length < 6) {
        callback(new Error('密码长度不足六位！'))
      } else if (value !== this.loginForm.pass) {
        callback(new Error("两次输入的密码不相同！"))
      } else {
        callback()
      }
    },
    validatePhoneNum: function(rule, value, callback) {
      if (value.toString() === '') {
        callback(new Error('请输入您的手机号码！'))
      } else if (value.toString().length !== 11) {
        callback(new Error('手机号码应为11位！'))
      } else {
        callback()
      }
    },
    resetForm: function() {
      this.$refs['loginFormRef'].resetFields();
    },
    closeDialog: function() {
      this.resetForm();
      this.$emit('closeDialog', false);
    },
    commit: function () {
      this.$refs.loginFormRef.validate((valid) => {
        if (valid) {
          if (this.labelPosition === "登录") {
            this.login();
          } else if (this.labelPosition === "注册") {
            this.signUp();
          }
        } else {
          this.$tipUtil.errTip("您输入的部分信息非法，请检查！");
        }
      });
    },
    login: function () {
      request({
        url: "/user/login",
        method: "post",
        data: {
          loginName: this.loginForm.account,
          password: this.loginForm.pass,
        },
      }).then((response) => {
        if (response.code === 200) {
          localStorage.setItem("identityCode", response.data.identityCode);
          localStorage.setItem("userLoginName", this.loginForm.account);
          localStorage.setItem("userHeader", response.data.img);
          localStorage.setItem("userNickname", response.data.nickname);
          localStorage.setItem("userPhoneNum", response.data.phoneNum);
          this.$tipUtil.successTip(response.msg);
          this.closeDialog();
          this.$router.replace({
            path: '/',
          })
        } else {
          this.$tipUtil.errTip(response.msg);
        }
      })
    },
    signUp: function () {
      request({
        url: "/user/register",
        method: "post",
        data: {
          identity: this.loginForm.identityCode.toString(),
          nickname: this.loginForm.nickname,
          loginName: this.loginForm.account,
          password: this.loginForm.pass,
          phoneNum: this.loginForm.phoneNum.toString(),
        },
      }).then((response) => {
        if (response.code === 200) {
          localStorage.setItem("identityCode", this.loginForm.identityCode.toString());
          localStorage.setItem("userLoginName", this.loginForm.account);
          localStorage.setItem("userHeader", response.data.img);
          localStorage.setItem("userNickname", response.data.nickname);
          localStorage.setItem("userPhoneNum", response.data.phoneNum);
          this.$tipUtil.successTip(response.msg);
          this.closeDialog();
          this.$router.replace({
            path: '/',
          })
        } else {
          this.$tipUtil.errTip(response.msg);
        }
      })
    }
  },
  setup() {
    return {
    };
  }
}
</script>

<style scoped>
</style>